﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace BuddHa.Wechat.Mini.Cryptography
{
    public class AESUtil
    {
        public static string? _key;

        public static string? _iv;

        public static PaddingMode _paddingMode;

        public static CipherMode _cipherMode;

        public AESUtil(string key, string iv, PaddingMode paddingMode, CipherMode cipherMode)
        {
            _key = key;
            _iv = iv;
            _paddingMode = paddingMode;
            _cipherMode = cipherMode;
        }

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="str">需要加密的字符串</param>
        /// <param name="key">32位密钥</param>
        /// <returns>加密后的字符串</returns>
        public string Encrypt(string inputdata)
        {
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(inputdata);
            byte[] keyArray = Convert.FromBase64String(_key);
            using (var aes = Aes.Create())
            {
                aes.Key = keyArray;
                aes.Mode = _cipherMode;
                aes.Padding = _paddingMode;
                if (!string.IsNullOrWhiteSpace(_iv))
                {
                    try
                    {
                        aes.IV = Encoding.UTF8.GetBytes(_iv);
                    }
                    catch (Exception)
                    {
                        aes.IV = Convert.FromBase64String(_iv);
                    }
                }
                ICryptoTransform cTransform = aes.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="str">需要解密的字符串</param>
        /// <param name="key">32位密钥</param>
        /// <returns>解密后的字符串</returns>
        public string Decrypt(string inputdata)
        {
            byte[] toDecryptArray = Convert.FromBase64String(inputdata);

            byte[] keyArray = Convert.FromBase64String(_key);
            using (var aes = Aes.Create())
            {
                aes.Key = keyArray;
                aes.Mode = _cipherMode;
                aes.Padding = _paddingMode;
                if (!string.IsNullOrWhiteSpace(_iv))
                {
                    aes.IV = Convert.FromBase64String(_iv);
                }
                ICryptoTransform cTransform = aes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
                return Encoding.UTF8.GetString(resultArray);
            }
        }
    }
}
